<template>
  <div class="index-card">
    <section>
      <ConditionBox>
        <template #left>
          <div class="title">实习评价评分规则</div>
        </template>
        <template #right>
          <a-button v-if="!props.review" @click="setRules" type="text"
            >设置</a-button
          >
        </template>
      </ConditionBox>
      <a-divider />
      <a-table :data="rulesData" :pagination="false" stripe>
        <template #columns>
          <a-table-column title="考核节点" align="center">
            <template #cell="{ rowIndex }">
              <span v-if="rowIndex === 0">考核评价</span>
              <span v-if="rowIndex === 1">员工自评</span>
            </template>
          </a-table-column>
          <a-table-column title="考核总分" align="center">
            <template #cell="">
              {{
                formData?.upperLimitScore ? formData?.upperLimitScore : '不限'
              }}
            </template>
          </a-table-column>
          <a-table-column title="评分计算方式" align="center">
            <template #cell="{}">
              <span v-if="formData?.scoreCalculation === 2"> 加权计算 </span>
              <span v-if="formData?.scoreCalculation === 1"> 加和计算 </span>
              <span v-if="!formData?.scoreCalculation">--</span>
            </template>
          </a-table-column>
          <a-table-column title="考核权重" align="center">
            <template #cell="{ rowIndex }">
              <span v-if="rowIndex === 0">
                {{ formData?.organizationEvaluation }} %
              </span>
              <span v-if="rowIndex === 1">
                <a-input-number
                  v-if="!props.review"
                  v-model="formData.selfEvaluation"
                  style="width: 80px"
                  @blur="weightChange"
                  hide-button
                >
                  <template #suffix> % </template>
                </a-input-number>
                <span v-else> {{ formData.selfEvaluation }} % </span>
              </span>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </section>
    <section>
      <ConditionBox :margin-top="20" :margin-bottom="20">
        <template #left>
          <div class="title">实习评价指标</div>
        </template>
        <template #right>
          <a-button v-if="!props.review" @click="quoteIndexLibrary" type="text"
            >引用指标库</a-button
          >
        </template>
      </ConditionBox>
      <a-divider />
      <a-table :data="formData?.indexArr" :pagination="false">
        <template #columns>
          <a-table-column :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column :width="200" data-index="name" title="指标名称">
          </a-table-column>
          <a-table-column :width="200" data-index="remark" title="指标描述">
          </a-table-column>
          <a-table-column
            :width="200"
            data-index=""
            title="评分标准"
            :headerCellStyle="{
              height: '30px'
            }"
          >
            <a-table-column
              :width="200"
              data-index="excellent"
              title="优秀A"
              :headerCellStyle="{
                height: '30px'
              }"
            >
            </a-table-column>
            <a-table-column
              :width="200"
              data-index="good"
              title="良好B"
              :headerCellStyle="{
                height: '30px'
              }"
            >
            </a-table-column>
            <a-table-column
              :width="200"
              data-index="qualified"
              title="合格C"
              :headerCellStyle="{
                height: '30px'
              }"
            >
            </a-table-column>
            <a-table-column
              :width="200"
              data-index="range"
              title="较差D"
              :headerCellStyle="{
                height: '30px'
              }"
            >
            </a-table-column>
            <a-table-column
              :width="200"
              data-index="wrong"
              title="差E"
              :headerCellStyle="{
                height: '30px'
              }"
            >
            </a-table-column>
          </a-table-column>
          <a-table-column :width="100" data-index="upperLimit" title="评分上限">
            <template #cell>
              {{ formData.upperLimitScore ? formData.upperLimitScore : '无限' }}
            </template>
          </a-table-column>
          <a-table-column :width="120" data-index="weight" title="指标权重%">
          </a-table-column>
          <a-table-column :width="300" data-index="name" title="评分人">
            <template #cell="{ record }">
              <a-space>
                <template v-for="user in record?.scorer" :key="user.id">
                  <a-tag color="arcoblue" :default-checked="true">
                    {{ user.userName }}({{ user.weight }}%)
                  </a-tag>
                </template>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column
            :width="120"
            data-index=""
            title="操作"
            fixed="right"
            align="center"
          >
            <template #cell="{ record, rowIndex }">
              <a-tooltip content="编辑">
                <IconFont
                  type="icon-edit"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                  @click="goEdit(record, rowIndex)"
                />
              </a-tooltip>
              <a-tooltip content="设置评分人">
                <!-- <IconFont
                  type="icon-xinzengkehu"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                /> -->
                <icon-user-add
                  :size="20"
                  style="color: #3c6eff"
                  @click="setScore(record, rowIndex)"
                />
              </a-tooltip>
              <a-tooltip content="删除" position="left">
                <a-popconfirm
                  content="是否确认删除该条数据?"
                  @ok="delIndex(rowIndex)"
                >
                  <icon-font
                    type="icon-delete"
                    :size="26"
                    :style="{
                      cursor: 'pointer',
                      marginRight: '10px'
                    }"
                  />
                </a-popconfirm>
              </a-tooltip>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div class="index-add">
        <a-button type="text" @click="addIndex">新增指标</a-button>
      </div>
    </section>
    <!-- <section>
      <ConditionBox :margin-top="20" :margin-bottom="20">
        <template #left>
          <div class="title">实习综合评价</div>
        </template>
      </ConditionBox>
      <a-divider />
      <a-textarea
        v-model="formData.customArr[0].text"
        placeholder="请输入评价内容"
        allow-clear
        :auto-size="{
          minRows: 4
        }"
      >
      </a-textarea>
    </section> -->

    <section v-for="(item, index) in formData.customArr" :key="index">
      <ConditionBox :margin-top="20" :margin-bottom="20">
        <template #left>
          <div class="title">
            <a-input
              placeholder="请输入名称"
              v-if="isCustomEdit && currCustomIndex === index"
              v-model="item.name"
              @change="changeName(index)"
            ></a-input>
            <span v-else> {{ item.name }}-评价人({{ item.userName }}) </span>
          </div>
        </template>
        <template #right>
          <a-tooltip content="编辑" v-if="index !== 0">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="goEditCustom(index)"
            />
          </a-tooltip>
          <a-tooltip content="设置评价人">
            <icon-user-add
              :size="20"
              style="color: #3c6eff"
              @click="setEvaluationHuman(index)"
            />
          </a-tooltip>
          <a-tooltip content="删除" v-if="index !== 0">
            <a-popconfirm
              content="是否确认删除该条数据?"
              @ok="delCustom(index)"
            >
              <icon-font
                type="icon-delete"
                :size="26"
                :style="{
                  cursor: 'pointer',
                  marginRight: '10px'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </ConditionBox>
      <a-divider />
      <a-textarea
        v-model="item.text"
        disabled
        placeholder="请输入评价内容"
        allow-clear
        :auto-size="{
          minRows: 4
        }"
      >
      </a-textarea>
    </section>
    <div class="custom-add">
      <a-button type="text" @click="addCustom">新增实习评价</a-button>
    </div>
  </div>
  <RulesDrawer
    v-model:visible="rulesVisible"
    v-model:data="formData"
    @change="changeRules"
  />
  <AddIndex
    v-model:visible="indexModalVisible"
    @indexEmit="indexEmit"
    :data="currIndexData"
  ></AddIndex>
  <IndexLibrary
    v-model:visible="indexLibraryVisible"
    @indexEmit="indexLibraryEmit"
  />
  <ScoreHumanModal
    ref="scoreHumanModalRef"
    v-model:visible="humanModalVisible"
    v-model:data="currIndexData"
    :type="1"
    @save="saveScoreHuman"
  />
  <SelectedScorerModal
    v-model:visible="evaluationHumanModalVisible"
    :data="uniqueArr"
    @submit="submitEvaluationEmit"
  />
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { PerformanceAssessmentTemplateDimensionality } from '@/apis/management/performance/baseSetting/template/type';
import RulesDrawer from '@/views/Management/Performance/PerformanceManagement/Probation/Components/AssessmentPlan/conponents/Tool/RulesDrawer.vue';
import AddIndex from './Components/AddIndex/index.vue';
import IndexLibrary from './Components/IndexLibrary/index.vue';
import ScoreHumanModal from './Components/ScoreHumanModal/index.vue';
import { Message } from '@arco-design/web-vue';
import { useVModel } from '@vueuse/core';
import SelectedScorerModal from './Components/SelectedScorerModal/index.vue';
import { getProbationToolName } from '@/utils/probation';

const props = withDefaults(
  defineProps<{
    data: any;
    // data?: PerformanceAssessmentTemplateDimensionality[];
    review?: boolean;
  }>(),
  {}
);

// 储存编辑时要删的数据orange
let delTypeIds = {
  type2Ids: [],
  type3Ids: [],
  type4Ids: []
};
const emit = defineEmits(['update:data']);

// const formData = reactive<any>({
//   data: {
//     organizationEvaluation: 100,
//     selfEvaluation: 0,
//     upperLimitType: 2,
//     scoreCalculation: 1,
//     indexArr: <any>[], // 指标表格
//     customArr: [] // 自定义表格
//   }
// });

const formData = useVModel(props, 'data', emit);

const columns = ref<any>([
  {
    title: '序号',
    dataIndex: '',
    slotName: 'index'
  },
  {
    title: '考核维度名称',
    dataIndex: 'name',
    slotName: 'name'
  },
  {
    title: '考核工具',
    dataIndex: 'type',
    slotName: 'type'
  },
  {
    title: '配分/权重',
    dataIndex: 'weight',
    slotName: 'weight'
  }
]);
onMounted(() => {
  if (!props.review) {
    columns.value.push({
      title: '操作',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 120
    });
  }
});
const weightChange = () => {
  if (!formData.value) return;
  if (!formData.value.selfEvaluation) {
    formData.value.organizationEvaluation = 0;
  }
  if (!formData.value.selfEvaluation) formData.value.selfEvaluation = 0;
  formData.value.organizationEvaluation = 100 - formData.value.selfEvaluation;
};
const changeRules = (data: any) => {
  const { upperLimitType, scoreCalculation, upperLimitScore } = data;
  formData.value.upperLimitType = upperLimitType;
  formData.value.scoreCalculation = scoreCalculation;
  formData.value.upperLimitScore = upperLimitScore;
};
const rulesData = [{}, {}];
const rulesVisible = ref(false);
const setRules = () => {
  rulesVisible.value = true;
};

let indexLibraryVisible = ref(false);
// 引用指标库
const quoteIndexLibrary = () => {
  indexLibraryVisible.value = true;
};

const indexLibraryEmit = (record: any) => {
  record.forEach((el: any) => {
    formData.value.indexArr.push(el);
  });
};

let indexModalVisible = ref(false); // 新增指标弹出框
let currIndexData = ref(); // 保存当前选中行的数据
let currIndex = ref(-1);
// 新增指标
const addIndex = () => {
  currIndexData.value = {
    name: '',
    remark: '',
    excellent: '',
    good: '',
    qualified: '',
    range: '',
    wrong: ''
  };
  currIndex.value = -1;
  indexModalVisible.value = true;
};

const indexEmit = (data: any) => {
  if (currIndex.value !== -1) {
    formData.value.indexArr[currIndex.value] = data;
  } else formData.value.indexArr.push(data);
};

// 编辑一项指标
const goEdit = (record: any, ind: number) => {
  currIndexData.value = record;
  currIndex.value = ind;
  indexModalVisible.value = true;
};

let humanModalVisible = ref(false);
let scoreHumanModalRef = ref();
// 设置评分人
const setScore = (record: any, ind: number) => {
  currIndexData.value = cloneDeep(record);
  currIndexData.value.scorer = currIndexData.value.scorer
    ? currIndexData.value.scorer
    : [];
  currIndexData.value.scorerStatus = currIndexData.value.scorerStatus || {
    appoint: { status: 2, weight: 0 },
    superiors: { status: 2, weight: 0 },
    junior: { status: 2, weight: 0 },
    peer: { status: 2, weight: 0 },
    other: { status: 2, weight: 0 }
  };
  currIndex.value = ind;
  humanModalVisible.value = true;
};

const saveScoreHuman = () => {
  if (scoreHumanModalRef.value.delIds.length > 0) {
    delTypeIds.type4Ids = scoreHumanModalRef.value.delIds;
  }
  formData.value.indexArr[currIndex.value] = currIndexData.value;

  // 每次设置完评分人都清空下面评价内容的指定评分人
  formData.value.customArr.forEach((el: any) => {
    el.userId = 0;
    el.userName = '';
  });
};

let uniqueArr = [];
const handleUnique = (arr: []) => {
  for (const obj of arr) {
    const exists = uniqueArr.some(
      (item) => item.name === obj.name && item.id === obj.id
    );
    if (!exists) {
      uniqueArr.push(obj);
    }
  }
};

// 删除一项指标
const delIndex = (ind: number) => {
  delTypeIds.type2Ids.push(formData.value.indexArr[ind].id);
  formData.value.indexArr.splice(ind, 1);
};

let isCustomEdit = ref(false); // 自定义指标是否可编辑
let currCustomIndex = ref(-1); // 判断第几个索引的自定义可以编辑
// 新增自定义评价
const addCustom = () => {
  formData.value.customArr.push({
    name: ''
  });
  isCustomEdit.value = true;
  currCustomIndex.value = formData.value.customArr.length - 1;
};

// 修改自定义名字输入框
const changeName = (ind: number) => {
  currCustomIndex.value = ind;
  isCustomEdit.value = false;
};

// 编辑自定义名字
const goEditCustom = (ind: number) => {
  currCustomIndex.value = ind;
  isCustomEdit.value = true;
};

let evaluationHumanModalVisible = ref(false); // 设置评价人弹出框

// 设置评价人
const setEvaluationHuman = (ind: number) => {
  const arr = []; // 用来储存所有选中的评价人（会重复）
  formData.value.indexArr.forEach((el: any) => {
    el.scorer.forEach((el2: any) => {
      arr.push({
        id: el2.userId,
        name: el2.userName
      });
    });
  });
  handleUnique(arr);
  console.log('===================indexArrindexArr=================');
  console.log(formData.value.indexArr);
  console.log(uniqueArr);
  console.log('====================================');
  currCustomIndex.value = ind;
  evaluationHumanModalVisible.value = true;
};

const submitEvaluationEmit = (data: any) => {
  formData.value.customArr[currCustomIndex.value].userId = data.id;
  formData.value.customArr[currCustomIndex.value].userName = data.name;
  console.log('====================================');
  console.log(formData.value.customArr[currCustomIndex.value]);
  console.log('====================================');
};

// 删除自定义项
const delCustom = (ind: number) => {
  delTypeIds.type3Ids.push(formData.value.customArr[ind].id);
  formData.value.customArr.splice(ind, 1);
};

const validate = () => {
  let isIndex100 = 0;
  formData.value.indexArr.forEach((el: any) => {
    isIndex100 += el.weight;
  });
  if (isIndex100 !== 100) {
    Message.error('实习评价指标权重之和应为100%');
    return true;
  }
  for (let i of formData.value.customArr) {
    if (!i.userId) {
      Message.error('请选择自定义指标的评价人');
      return true;
    }
  }
};

defineExpose({
  delTypeIds,
  validate
});
</script>

<style lang="less" scoped>
.index-card {
  border-radius: 4px;

  // margin: 20px 0;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  padding: 20px;
  .title {
    font-weight: 600;
    font-size: 18px;
  }
}

.index-add,
.custom-add {
  width: calc(100% - 2px);
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px solid #eee;
}

.custom-add {
  background-color: #e5f1ff;
  margin-top: 20px;
}
</style>
